package com.yxw.yx_hotel.service.impl;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxw.yx_hotel.dto.hotel_tenant.HotelTenantAddDTO;
import com.yxw.yx_hotel.dto.hotel_tenant.HotelTenantDeleteDTO;
import com.yxw.yx_hotel.dto.hotel_tenant.HotelTenantQueryDTO;
import com.yxw.yx_hotel.dto.hotel_tenant.HotelTenantUpdateDTO;
import com.yxw.yx_hotel.entity.YxHotelTenantEntity;
import com.yxw.yx_hotel.entity.YxSysUserEntity;
import com.yxw.yx_hotel.exception.GlobalCustomerException;
import com.yxw.yx_hotel.mapper.HotelTenantMapper;
import com.yxw.yx_hotel.mapper.UserMapper;
import com.yxw.yx_hotel.service.HotelTenantService;
import com.yxw.yx_hotel.utils.AssertUtil;
import com.yxw.yx_hotel.utils.PageUtils;
import com.yxw.yx_hotel.utils.UserUtil;
import com.yxw.yx_hotel.vo.YxHotelTenantVO;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.enums.ErrorCodeEnum;
import com.yxw.yxnet_cd_center.common.utils.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author fangmaoxin
 * @version 1.0
 * @date 2024年1月22日
 * 客户管理相关
 */
@Service
@Slf4j
public class HotelTenantServiceImpl extends ServiceImpl<HotelTenantMapper, YxHotelTenantEntity> implements HotelTenantService {

    @Autowired
    private HotelTenantMapper hotelTenantMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserUtil userUtil;

    /**
     * 查询客户列表
     */
    @Override
    public PageVO<YxHotelTenantVO> listTenants(HotelTenantQueryDTO queryDTO) {
        checkLoginUserIsAdmin(); // 校验操作人是不是saas管理员
        Page<YxHotelTenantEntity> page = new Page<>(queryDTO.getCurrPage(), queryDTO.getPageSize());
        List<YxHotelTenantVO> result = hotelTenantMapper.listTenants(page, queryDTO);
        return PageUtils.get(page, result);
    }

    /**
     * 添加客户
     */
    @Override
    @Transactional
    public void addTenant(HotelTenantAddDTO dto) {
        checkLoginUserIsAdmin(); // 校验操作人是不是saas管理员
        YxHotelTenantEntity result = getYxHotelTenantEntity(dto);
        YxHotelTenantEntity phone = baseMapper.selectOne(new QueryWrapper<YxHotelTenantEntity>().eq("phone", dto.getPhone()));
        AssertUtil.isNull(phone, ErrorCodeEnum.PHONE_IS_REGISTERED);
        baseMapper.insert(result);
        // 获取自动生成的主键值
        Long tenantId = result.getTenantId();
        // 插入user表
        YxSysUserEntity userNum = userMapper.selectOne(new QueryWrapper<YxSysUserEntity>().eq("user_num", dto.getUserNum()));
        AssertUtil.isNull(userNum, ErrorCodeEnum.USER_NUM_IS_EXISTS);
        YxSysUserEntity mobilePhone = userMapper.selectOne(new QueryWrapper<YxSysUserEntity>().eq("mobile_phone", dto.getPhone()).eq("tenant_id", tenantId));
        AssertUtil.isNull(mobilePhone, ErrorCodeEnum.PHONE_IS_REGISTERED);
        YxSysUserEntity user = getUserEntity(dto, tenantId);
        Long userId = user.getUserId();
        String newPassword = PasswordUtil.signUserPassword(userId, dto.getPassword());
        LambdaUpdateWrapper<YxSysUserEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(YxSysUserEntity::getUserId, userId)
                .set(YxSysUserEntity::getPassword, newPassword);
        userMapper.update(null, updateWrapper);
    }

    /**
     * 校验操作人是不是saas管理员
     */
    private void checkLoginUserIsAdmin() {
        Long adminId = userUtil.getLoginUserId();
        AssertUtil.isNotNull(adminId, ErrorCodeEnum.COLLECTION_USER_ID_ERROR);
        LambdaQueryWrapper<YxSysUserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YxSysUserEntity::getUserId, adminId);
        YxSysUserEntity admin = userMapper.selectOne(wrapper);
        if (null == admin || !Integer.valueOf(2).equals(admin.getUserType())) {
            throw new GlobalCustomerException(ErrorCodeEnum.ILLEGAL_OPERATION);
        }
    }

    /**
     * 封装user实体，插入user表数据
     */
    private YxSysUserEntity getUserEntity(HotelTenantAddDTO dto, Long tenantId) {
        YxSysUserEntity user = new YxSysUserEntity();
        user.setMobilePhone(dto.getPhone());
        user.setUserIdentity(null);
        user.setPassword(dto.getPassword());
        user.setUserNum(dto.getUserNum());
        user.setUserStatus(1);
        user.setParentUserId(null);
        user.setEmail(null);
        user.setUserName(dto.getUserName());
        user.setIdentityCardNo(null);
        user.setCreateTime(new Date());
        user.setUserType(1);
        user.setTenantId(tenantId);
        user.setStartTime(dto.getStartTime());
        user.setEndTime(dto.getEndTime());
        user.setCreateUserName("系统");
        userMapper.insert(user);
        return user;
    }

    /**
     * 封装HotelTenant实体 客户数据
     */
    private static YxHotelTenantEntity getYxHotelTenantEntity(HotelTenantAddDTO dto) {
        YxHotelTenantEntity result = new YxHotelTenantEntity();
        result.setTenantName(dto.getTenantName());
        result.setUserName(dto.getUserName());
        result.setPhone(dto.getPhone());
        result.setStartTime(dto.getStartTime());
        result.setEndTime(dto.getEndTime());
        result.setStatus(1);
        result.setCreateTime(new Date());
        result.setAddress(dto.getAddress());
        result.setWholeName(dto.getWholeName());
        result.setResource(dto.getResource());
        return result;
    }

    /**
     * 修改客户
     */
    @Override
    @Transactional
    public void updateTenant(HotelTenantUpdateDTO dto) {
        YxHotelTenantEntity entity = baseMapper.selectById(dto.getTenantId());
        AssertUtil.isNotNull(entity, ErrorCodeEnum.TENANT_ID_ERROR);
        hotelTenantMapper.updateTenant(dto);
        YxSysUserEntity user = userMapper.selectOne(new QueryWrapper<YxSysUserEntity>().eq("tenant_id", dto.getTenantId()).eq("user_id", dto.getUserId()));
        AssertUtil.isNotNull(user, ErrorCodeEnum.USER_ID_ERROR);
        user.setUserName(StringUtils.isNotEmpty(dto.getUserName()) ? dto.getUserName() : user.getUserName());
        user.setUserNum(StringUtils.isNotEmpty(dto.getUserNum()) ? dto.getUserNum() : user.getUserNum());
        user.setMobilePhone(StringUtils.isNotEmpty(dto.getPhone()) ? dto.getPhone() : user.getMobilePhone());
        if (null != dto.getStatus()) {
            user.setUserStatus(dto.getStatus());
        }
        if (null != dto.getPassword()) {
            String newPassword = PasswordUtil.signUserPassword(user.getUserId(), dto.getPassword());
            user.setPassword(newPassword);
        }
        userMapper.updateById(user);
    }

    /**
     * 删除客户
     */
    @Override
    @Transactional
    public void deleteTenant(HotelTenantDeleteDTO dto) {
        YxHotelTenantEntity entity = baseMapper.selectById(dto.getTenantId());
        AssertUtil.isNotNull(entity, ErrorCodeEnum.TENANT_ID_ERROR);
        YxSysUserEntity user = userMapper.selectOne(new QueryWrapper<YxSysUserEntity>().eq("tenant_id", dto.getTenantId()).eq("user_id", dto.getUserId()));
        AssertUtil.isNotNull(user, ErrorCodeEnum.USER_ID_ERROR);
        userMapper.deleteById(user);
        hotelTenantMapper.deleteTenant(dto);
    }
}
